package com.tablefood.dao.Impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SessionFactory;

import com.tablefood.dao.FavoriteDao;
import com.tablefood.domain.ShopCart;
import com.tablefood.domain.ShopFavorite;

public class FavoriteDaoImpl implements FavoriteDao {

	@Resource
	private SessionFactory sessionFactory; 
	
	@Override
	public boolean addFavorite(ShopFavorite favorite) {
		
		try{
		sessionFactory.getCurrentSession().save(favorite);
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@Override
	public ShopFavorite searchByProductid(String productid) {
		
		String hql = "from ShopFavorite fav where fav.shopProduct.productid=?";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		query.setString(0, productid);
		
		if(query.list().size()>0){
			List<ShopFavorite> list = query.list();
			ShopFavorite fav = list.get(0);
			return fav;
		}
		return null;
	}

	@Override
	public List<ShopFavorite> queryForPage(String hql, String userid, int offset,
			int length) {
		
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		query.setString(0, userid);
		query.setFirstResult(offset);
		query.setMaxResults(length);
		List<ShopFavorite> list = query.list();
		
		return list;
	}

	@Override
	public int getAllRowCount(String hql, String userid) {
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		query.setString(0, userid);
		return query.list().size();
	}

	@Override
	public boolean delFavorite(ShopFavorite favorite) {
		
		try{
			sessionFactory.getCurrentSession().delete(favorite);
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
		
		return true;
	}



	

	 
	 

}
